class Solution {
public:
    string simplifyPath(string path) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> paths;
        int n = path.length();

        paths.push_back("/");
        for (int i = 1; i < n; ) {
            int j = i;
            while (j < n && path[j] != '/') {
                ++j;
            }
            string cur = path.substr(i, j - i);
            if (cur == "..") {
                if (paths.size() > 1) {
                    paths.pop_back();
                }
            } else if (cur != "." && cur != "") {
                paths.push_back(cur);
            }
            i = j + 1;
        }

        string ans = "/";
        for (int i = 1; i < paths.size(); ++i) {
            if (i > 1) {
                ans += "/" + paths[i];
            } else {
                ans += paths[i];
            }
        }
        return ans;
    }
};
